package cn.information.view.SR;

import cn.information.utils.DButil;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class ProfitUI extends JFrame {
    private JTable table;
    private JScrollPane scrollPane;
    private JButton btnRefresh;
    private JLabel lblTotalProfit;
    private JPanel panelBottom;
    private DecimalFormat df = new DecimalFormat("#,##0.00");

    public ProfitUI() {
        setTitle("利润统计");
        setSize(900, 500);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        table = new JTable();
        scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        panelBottom = new JPanel(new BorderLayout());

        JPanel panelTotal = new JPanel(new FlowLayout(FlowLayout.CENTER));
        lblTotalProfit = new JLabel("总利润: ¥0.00");

        lblTotalProfit.setForeground(Color.RED);
        panelTotal.add(lblTotalProfit);
        panelBottom.add(panelTotal, BorderLayout.CENTER);

        JPanel panelButtons = new JPanel(new FlowLayout(FlowLayout.CENTER));
        btnRefresh = new JButton("刷新数据");
        JButton btnExit = new JButton("退出");

        btnRefresh.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadProfitData();
            }
        });

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        panelButtons.add(btnRefresh);
        panelButtons.add(btnExit);
        panelBottom.add(panelButtons, BorderLayout.SOUTH);

        add(panelBottom, BorderLayout.SOUTH);
        loadProfitData();
    }

    private void loadProfitData() {
        List<Object[]> profitData = new ArrayList<>();
        double totalProfit = 0.0;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = DButil.getConnection();
            String sql = "SELECT p.spid, pu.gkname, p.spname, " +
                    "(pu.spprice - p.spprice) AS profit, " +
                    "p.SL, pu.spnumber " +
                    "FROM purchase_info pu " +
                    "JOIN product_info p ON pu.spid = p.spid";

            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();

            while (rs.next()) {
                Object[] row = new Object[6];
                row[0] = rs.getInt("spid");          // 商品ID
                row[1] = rs.getString("gkname");      // 顾客姓名
                row[2] = rs.getString("spname");      // 商品名称

                double profitPerItem = rs.getDouble("profit");
                int quantity = rs.getInt("spnumber");
                double totalProfitForItem = profitPerItem * quantity;

                row[3] = df.format(profitPerItem) + " (总: " + df.format(totalProfitForItem) + ")"; // 利润
                row[4] = rs.getString("SL");          // 保质期
                row[5] = quantity;                    // 数量

                profitData.add(row);
                totalProfit += totalProfitForItem;
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据加载失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
            DButil.close(conn);
        }
        table.setModel(new ProfitTableModel(profitData));
        lblTotalProfit.setText("总利润: ¥" + df.format(totalProfit));
    }

    private static class ProfitTableModel extends AbstractTableModel {
        private final String[] columnNames = {"商品ID", "顾客姓名", "商品名称", "利润(单价利润 × 数量)", "保质期", "数量"};
        private final List<Object[]> data;

        public ProfitTableModel(List<Object[]> data) {
            this.data = data;
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data.get(rowIndex)[columnIndex];
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 5) return Integer.class; // 数量列
            return String.class;
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ProfitUI().setVisible(true);
            }
        });
    }
}